package ip.controller;
/***********************************************************************
 * Module:  CreateLanguageController.java
 * Author:  mojsilo
 * Purpose: Defines the Class CreateLanguageController
 ***********************************************************************/

import ip.command.CreateLanguageCommand;
import ip.dto.LanguageDTO;
import ip.dto.UserDTO;
import ip.exceptions.ApplicationException;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * @web.servlet
 * 	name="CreateLanguageController"
 * @web.servlet-mapping
 * 	url-pattern="/control/CreateLanguage"
 */
public class CreateLanguageController extends HttpServlet
{
	
	private static final long serialVersionUID = 6077656427217112236L;
	private Logger logger = Logger.getLogger(this.getClass());
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try{
			logger.info("doGet(...)");
			HttpSession session = request.getSession(true);      
			UserDTO adminDto = (UserDTO) session.getAttribute("administrator");			

			if(adminDto == null){
				response.sendRedirect(response.encodeRedirectURL("../jsp/login_administrator.jsp"));
				return;
			}
			LanguageDTO languageDTO = new LanguageDTO();
			languageDTO.setName(request.getParameter("name"));
			
			logger.debug("doGet(...) - languageDTO: "+languageDTO);
			CreateLanguageCommand createLanguageCommand = new CreateLanguageCommand();
			createLanguageCommand.setLanguageDTO(languageDTO);
			createLanguageCommand.init();
			createLanguageCommand.execute();
			createLanguageCommand.dispose();
			getServletConfig().getServletContext().getRequestDispatcher("/control/Languages").forward(request, response);
		}
		catch (ApplicationException e) {
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}
		catch (Exception e) {
			logger.error(e);
			request.setAttribute("error", "Unexpected error!!");//kako ovo bolje odraditi???
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}


	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		logger.info("doPost(...)");
		doGet(request, response);
	}

}